{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# ERNIE Bot 搜索能力\n",
    "\n",
    "搜索能力在大模型中扮演着关键的角色，它能够借助搜索引擎，让模型可以获得实时信息，从而更全面地理解问题，做出更准确的预测和决策。\n",
    "\n",
    "现在，ERNIE Bot 和 ERNIE Bot 4.0 都已经支持了搜索能力，这一功能默认开启，无需额外设置模型即可返回更为准确的结果。\n",
    "\n",
    "注意：需要 SDK 版本 >= 0.1.4"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "os.environ[\"QIANFAN_AK\"] = \"your_app_ak\"\n",
    "os.environ[\"QIANFAN_SK\"] = \"your_app_sk\"\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import qianfan\n",
    "\n",
    "# 为了更佳的展示效果，这里我们先定义一个展示 Markdown 的函数\n",
    "from IPython.display import Markdown, display\n",
    "\n",
    "def print_md(text):\n",
    "    display(Markdown(text))\n",
    "\n",
    "r = qianfan.ChatCompletion(model=\"ERNIE-Bot-4\").do(messages=[{\n",
    "    \"role\":\"user\",\n",
    "    \"content\": \"林俊杰2023演唱会安排\"\n",
    "}])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "林俊杰2023年的演唱会安排如下：\n",
       "\n",
       "* 上海站：8月19日、20日\n",
       "* 广州站：9月8日、10日\n",
       "* 北京站：9月23日、24日\n",
       "* 西安站：10月28日、29日\n",
       "* 南京站：11月11日\n",
       "* 武汉站：11月25日、26日\n",
       "* 南宁站：12月9日、10日\n",
       "\n",
       "以上是林俊杰在2023年的部分演唱会安排，具体时间和地点可能因实际情况有所调整。建议关注林俊杰的官方社交媒体或相关票务平台，以获取最新和详细的演唱会信息。"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "print_md(r['result'])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 引用"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "为了更好的展现搜索结果的准确性，我们可以开启引用，这样模型的输出会通过角标展示所引用的搜索结果，方便用户寻找相关信息并甄别信息准确性。\n",
    "\n",
    "而开启引用，我们只需要在调用模型时，传入参数 `enable_citation` 即可。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "r = qianfan.ChatCompletion(model=\"ERNIE-Bot-4\").do(messages=[{\n",
    "    \"role\":\"user\",\n",
    "    \"content\": \"新能源汽车的优势\"\n",
    "}], enable_citation=True)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这样我们就可以在模型输出中看到角标，在 `['search_info']['search_results']` 字段中，我们可以拿到每个角标所引用的网址链接、标题等信息。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "新能源汽车的优势如下^[1][2]^：\n",
       "\n",
       "* **环保**：新能源汽车使用电力或其他清洁能源，显著降低了碳排放，保护了大气环境。\n",
       "* **省钱**：新能源汽车的耗电量低于燃油汽车的耗油量，可以节省费用。\n",
       "* **不限行**：新能源汽车几乎零污染、零排放，不在交通限行范围内。\n",
       "* **效率高**：新能源汽车将电能转化为动能的效率通常超过90%。\n",
       "* **噪音低**：新能源汽车的噪音很小，提高了驾驶的舒适性。\n",
       "* **保养简单**：新能源汽车的保养以检查为主，相对于燃油汽车保养更简单。\n",
       "* **有国家补贴政策**：新能源汽车可以享受购车补贴、减税优惠等。"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/markdown": [
       "[1] [新能源车的优势,看完这篇文章你就知道了](https://baijiahao.baidu.com/s?id=1777609954009780305&wfr=spider&for=pc)"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/markdown": [
       "[2] [新能源汽车的优势和劣势是什么](https://baijiahao.baidu.com/s?id=1752168697396988413&wfr=spider&for=pc)"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "print_md(r['result'])\n",
    "\n",
    "# 打印 Markdown 格式的链接\n",
    "for item in r['search_info']['search_results']:\n",
    "    print_md(\"[{}] [{}]({})\".format(item['index'], item['title'], item['url']))"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 关闭搜索能力"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在特殊的场景下，可能会希望关闭模型的搜索功能，可以通过传入参数 `disable_search` 实现。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "r = qianfan.ChatCompletion(model=\"ERNIE-Bot-4\").do(messages=[{\n",
    "    \"role\":\"user\",\n",
    "    \"content\": \"林俊杰2023演唱会安排\"\n",
    "}], disable_search=True)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "⚠️注意！此时模型将无法获取实时信息，仅能根据训练数据进行判断，因此涉及实时的最新信息输出结果可能会不准确，请注意甄别！"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": []
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## ERNIE-Bot-turbo开启搜索："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "**2024年的法定假日列表包括元旦、春节、清明节、劳动节、端午节和中秋节**。具体而言，元旦节是在1月1日放假，与周末连休；春节是从2月10日至17日放假调休，共8天，其中2月4日（星期日）、2月18日（星期日）上班；清明节是从4月4日至6日放假调休，共3天，4月7日（星期日）上班；劳动节是从5月1日至5日放假调休，共5天，4月28日（星期日）、5月11日（星期六）上班；端午节是从6月10日放假，与周末连休；最后，中秋节是从9月15日至17日放假调休，共3天，9月14日（星期六）上班^[1]^。"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tools_info: {'name': 'baidu_search', 'rewrite_query': '2024法定假日列表？', 'baidu_search': [{'index': 1, 'url': 'https://baijiahao.baidu.com/s?id=1780711643208353524&wfr=spider&for=pc', 'title': '2024年放假安排来了!'}]}\n"
     ]
    }
   ],
   "source": [
    "from IPython.display import Markdown, display\n",
    "from qianfan import ChatCompletion\n",
    "\n",
    "chat_comp = ChatCompletion()\n",
    "tools = [\n",
    "    {\n",
    "        \"type\": \"tool\",\n",
    "        \"tool\": {\n",
    "            \"name\": \"baidu_search\",\n",
    "            \"baidu_search\": {\n",
    "                \"top_n\": 1\n",
    "            }\n",
    "        }\n",
    "    }\n",
    "]\n",
    "\n",
    "from qianfan import QfMessages\n",
    "msgs = QfMessages()\n",
    "msgs.append(\"2024法定假日列表？\", \"user\")\n",
    "\n",
    "resp = chat_comp.do(msgs, tools=tools, tool_choice={\n",
    "    \"type\": \"tool\",\n",
    "    \"tool\": {\n",
    "        \"name\": \"baidu_search\"\n",
    "    }\n",
    "})\n",
    "\n",
    "display(Markdown(resp[\"result\"]))\n",
    "print(\"tools_info:\", resp[\"tools_info\"])"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.5"
  },
  "orig_nbformat": 4,
  "vscode": {
   "interpreter": {
    "hash": "58f7cb64c3a06383b7f18d2a11305edccbad427293a2b4afa7abe8bfc810d4bb"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
